package cn.huiyunche.base.service.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @FileName: cn.huiyunche.service.base.utils
 * @Description: Description
 * @author: Aaron
 * @date: 2016/11/2 下午6:45
 */
public class HttpRequestUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestUtil.class);

    //连接超时时间
    private static final int CONNECT_TIMEOUT = 10000;

    public static String sendHttpPost(final String url, final Map<String, Object> paramsMap, final int socketTimeout) {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);

        RequestConfig.Builder builder = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(socketTimeout);
        httpPost.setConfig(builder.build());

        List<NameValuePair> formParams = new ArrayList<>();
        if (paramsMap != null) {
            Set<String> set = paramsMap.keySet();
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object value = paramsMap.get(key);
                formParams.add(new BasicNameValuePair(key, null == value ? null : value.toString()));
            }
        }

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            return assemblyRetrunData(httpResponse);
        } catch (ClientProtocolException e) {
            LOGGER.error("HttpRequestUtil error : {}", e);
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("HttpRequestUtil error : {}", e);
            e.printStackTrace();
        } catch (IOException e) {
            LOGGER.error("HttpRequestUtil error : {}", e);
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static String assemblyRetrunData(CloseableHttpResponse httpResponse) {

        StatusLine statusLine = httpResponse.getStatusLine();

        //组装返回数据
        //success messagecode message data

        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        if (200 == statusLine.getStatusCode()) {
            map.put("success", true);
            try {
                HttpEntity entity = httpResponse.getEntity();
                map.put("data", entity != null ? EntityUtils.toString(entity) : null);
            } catch (IOException e) {
                LOGGER.error("assemblyRetrunData error : {}", e);
                e.printStackTrace();
            } finally {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    LOGGER.error("assemblyRetrunData error : {}", e);
                    e.printStackTrace();
                }
            }
        }

        map.put("messagecode", statusLine.getStatusCode());
        map.put("message", statusLine.getReasonPhrase());

        return JSONObject.toJSONString(map);
    }

//    public static String sendHttpsPost(final String url, final Map<String, Object> paramsMap) {
//
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        HttpPost httpPost = new HttpPost(url);
//
//        List<NameValuePair> formParams = new ArrayList<>();
//        if(paramsMap!=null){
//            Set set = paramsMap.keySet();
//            Iterator iterator = set.iterator();
//            while (iterator.hasNext()) {
//                Object key = iterator.next();
//                Object value = paramsMap.get(key);
//                formParams.add(new BasicNameValuePair(key.toString(), null==value?null:value.toString()));
//            }
//        }
//
//        try{
//            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
//            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
//            try {
//                HttpEntity entity = httpResponse.getEntity();
//                String result = EntityUtils.toString(entity, "UTF-8");
//                return result;
//            }finally {
//                httpResponse.close();
//            }
//        } catch (ClientProtocolException e) {
//            LOGGER.error("HttpRequestUtil error : {}", e);
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException e) {
//            LOGGER.error("HttpRequestUtil error : {}", e);
//            e.printStackTrace();
//        } catch (IOException e) {
//            LOGGER.error("HttpRequestUtil error : {}", e);
//            e.printStackTrace();
//        } finally {
//            // 关闭连接,释放资源
//            try {
//                httpClient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return null;
//    }
}
